var homeJs = function (targetObj) {
    x18n.set("zh-CN");
    this.targetObj = targetObj;
    this.showLeftRight = false;
    this.userDefault();
    this.leftMenu();
    this.leftFlag = true;
    this.init();
    return this;
};

homeJs.prototype = {
    init: function () {
        var data = new Object();
        data.systemName = '测试';
        data.resourceList = [{
            resourceName: '子菜单'
        }];
        this.targetObj.find("#loginOut").bind("click", this, this.loginOut);
        this.targetObj.find(".password_cont").find(".submit").bind("click", this, this.changePassword);
        this.addLeftClick();//绑定标签的左右移动事件
        this.bindDivShowTime();//显示系统时间
        setInterval('homeJsIn.bindDivShowTime(homeJsIn)', 1000);//1000毫秒刷新
        var that = this;
    },
    userDefault: function () {
        var userName = user['userName'];
        var userAccount = user['userAccount'];
        var userLogoUrl = user['userLogo'];
        this.targetObj.find("div.user-info").find("div.name").html("您好，" + userName);
        if (!isEmpty(userLogoUrl)) {
            this.targetObj.find("div.user-info").find("div.img").find("img").attr("src", userLogoUrl);
        }
        this.targetObj.find(".password_cont").find("input[name='userName']").attr("value", userName);
        this.targetObj.find(".password_cont").find("input[name='userAccount']").attr("value", userAccount);
    },
    /**左侧菜单*/
    leftMenu: function () {
        var that = this;
        let url = baseApiPath + "basSystemResource/MenuList/" + user["id"];
        JsonpAjax(url, null, function (result) {
            if (result.constructor == Object) {
                //先显示系统在显示系统下相关资源
                var minSystemManage = null;
                var minSort = 999;
                var arraySystem = new Array();
                var counts = 0;
                var systemPanel = that.targetObj.find(".system-panel");
                var list = {};
                if (result.code == 0) {
                    list = result.data;
                    for (var i = 0; i < list.length; i++) {
                        var systemManage = list[i]
                        if (minSort > systemManage["systemSort"]) {
                            minSort = systemManage["systemSort"];
                            minSystemManage = systemManage;
                        }
                        var dl = $("<dl id=" + systemManage["systenCode"] + "><dt><img src='images/" + systemManage["systenCode"] + ".png'/><dd>" + systemManage["systemName"] + "</dd></dt></dl>");
                        dl.bind("click", that.systemSwitchClick);
                        dl.data("systemCode", systemManage)
                        systemPanel.append(dl);
                    }
                    systemPanel.find("#" + minSystemManage["systenCode"]).addClass("click");
                    that.createLeftMenuHtml(minSystemManage);
                    that.oldSystemCode = minSystemManage["systenCode"];
                }
            }
        }, "GET");
    },
    /**
     * 系统切换方法
     */
    systemSwitchClick: function (e) {
        var dl = $(e.target).parents("dl");
        if (dl.length == 0) {
            dl = $(e.target);
        }
        var systemManage = dl.data("systemCode");
        if (homeJsIn.oldSystemCode == systemManage["systenCode"]) return;
        var systemPanel = homeJsIn.targetObj.find(".system-panel");
        systemPanel.find(".click").removeClass("click");
        dl.addClass("click");
        homeJsIn.targetObj.find(".leftsidebar_box").fadeOut(function () {
            $(this).empty();
            homeJsIn.createLeftMenuHtml(systemManage);
            $(this).fadeIn();
            homeJsIn.oldSystemCode = systemManage["systenCode"];
        });
    },
    /**
     * 生成左侧菜单Html代码
     */
    createLeftMenuHtml: function (minSystemManage) {
        var resources = minSystemManage["resourceList"];
        for (var i = 0; i < resources.length; i++) {
            var dl = $('<dl></dl>');
            var dt = $('<dt><span class="menuIcon"><img src="' + resources[i].imgUrl + '" /></span>' + resources[i].resourceName + '<span class="arrowIcon"><img src="images/select_xl01.png"></span></dt>');
            dl.append(dt);
            var data = resources[i].resourceList;
            if (null != data && undefined != data) {
                for (var j = 0; j < data.length; j++) {
                    var dd = $('<dd class="first_dd"><a href="#" data-url="' + data[j].resourcePath + '" data-code="' + data[j].resourceCode + '" data-id="' + data[j].id + '">' + data[j].resourceName + '</a></dd>');
                    dl.append(dd);
                }
            }
            $(".leftsidebar_box").append(dl);
        }
        //左侧菜单初始化折叠
        homeJsIn.targetObj.find(".leftsidebar_box dt .arrowIcon img").attr("src", "images/select_xl01.png");
        homeJsIn.targetObj.find(".leftsidebar_box dd").hide();
        homeJsIn.targetObj.find(".leftsidebar_box dt").bind("click", homeJsIn, homeJsIn._leftMenuClick);
        //给标签绑定点击事件
        homeJsIn.targetObj.find("dd.first_dd").find("a").bind("click", homeJsIn, homeJsIn.openRightHtml);
    },
    /**
     * 点击左侧菜单伸缩
     * */
    _leftMenuClick: function (e) {
        var that = e.data;
        that.targetObj.find(".leftsidebar_box dt").css({"background-image": "url('images/sidemenubg-1.png')"})
        $(this).css({"background-image": "url('images/sidemenubg-2.png')"});
        $(this).parent().find('dd').removeClass("menu_chioce");
        that.targetObj.find(".leftsidebar_box dt .arrowIcon img").attr("src", "images/select_xl01.png");
        $(this).parent().find('.arrowIcon img').attr("src", "images/select_xl.png");
        that.targetObj.find(".menu_chioce").slideUp();
        $(this).parent().find('dd').slideToggle();
        $(this).parent().find('dd').addClass("menu_chioce");
    },
    /**
     * 修改密码
     */
    changePassword: function (e) {
        var that = e.data;
        var pssword = that.targetObj.find(".password_cont").find("input[name='password']");
        var oldPassword = pssword.val().trim();
        if (isEmpty(oldPassword)) {
            notification({title: "操作失败", message: "请填写旧密码!!"}, "info");
            return;
        }
        var newPass = that.targetObj.find(".password_cont").find("input[name='newPassword']");
        var cknewPas = that.targetObj.find(".password_cont").find("input[name='ckNewPassword']");
        var newPassword = newPass.val().trim();
        var ckNewPassword = cknewPas.val().trim();
        if (isEmpty(newPassword)) {
            notification({title: "操作失败", message: "新密码不能为空!!"}, "info");
            return;
        }
        if (newPassword != ckNewPassword) {
            notification({title: "操作失败", message: "两次密码输入不一致!!"}, "info");
            return;
        }
        var reg = "^[A-Za-z0-9-_]*$";
        if (null == newPassword.match(reg)) {
            notification({title: "操作失败", message: "修改密码为必填项且只能为字母、数字、中划线、下划线"}, "info");
            return;
        }
        if (null == oldPassword.match(reg)) {
            notification({title: "操作失败", message: "旧密码为必填项且只能为字母、数字、中划线、下划线"}, "info");
            return;
        }
        var json = new Object();
        var userAccount = that.targetObj.find(".password_cont").find("input[name='userAccount']").val().trim();
        json["oldPassword"] = oldPassword;
        json["newPassword"] = newPassword;
        json["userAccount"] = userAccount;
        //修改密码
        JsonpAjax(baseApiath + "user/updatePwd", JSON.stringify(json), "json", function (result) {
            if (result.success) {
                //清空原先填入的值
                pssword.val("");
                newPass.val("");
                cknewPas.val("");
                notification({title: "操作成功", message: result.msg}, "success");
            } else {
                notification({title: "操作失败", message: result.msg}, "info");
            }
        });
    },
    /**
     * 退出登录
     */
    loginOut: function (e) {
        notification({title: "退出系统", message: "是否确定退出系统？"}, "confirm", {
            callback: function () {
                JsonpAjax(baseApiPath + "loginOut", null, "json", function (result) {
                    window.location.href = "login.html";
                });
            }
        })
    },
    bindDivShowTime: function () {
        var timeClockDiv = this.targetObj.find(".menu-time").find(".clock");
        var timeDateDiv = this.targetObj.find(".menu-time").find(".date");
        timeClockDiv.empty();
        timeDateDiv.empty();
        var today = new Date();
        var day;
        if (today.getDay() == 0) {
            day = "星期日";
        }
        if (today.getDay() == 1) {
            day = "星期一";
        }
        if (today.getDay() == 2) {
            day = "星期二";
        }
        if (today.getDay() == 3) {
            day = "星期三";
        }
        if (today.getDay() == 4) {
            day = "星期四";
        }
        if (today.getDay() == 5) {
            day = "星期五";
        }
        if (today.getDay() == 6) {
            day = "星期六";
        }
        var hours = today.getHours() + "";
        var minutes = today.getMinutes() + "";
        var seconds = today.getSeconds() + "";
        timeClockDiv.append((hours.length == 1 ? "0" + hours : hours) + ":" + (minutes.length == 1 ? "0" + minutes : minutes) + ":" + (seconds.length == 1 ? "0" + seconds : seconds));
        timeDateDiv.append(today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + day);

    },
    /***
     * 点击左侧菜单打开对应的界面
     * */
    openRightHtml: function (e) {
        var that = e.data;
        var clickObj = e.currentTarget;
        that.targetObj.find("#rightDataDiv").find("#indexHOMEDiv").hide();//隐藏HOME页
        that.targetObj.find("#homeSection").hide();//隐藏HOME页
        that.targetObj.find("#containsSection").show();
        //右侧显示界面
        var nowOpendRel = "";
        var openDataiv = that.targetObj.find("div.middleSlide").find("ul>li[class='select']");//当前选中打开的标签页
        if (!isEmpty(openDataiv)) {
            nowOpendRel = openDataiv.attr("data-code");//获取当前选中窗口的rel
        }
        var dataId = $(clickObj).attr("data-id");
        var dataCode = $(clickObj).attr("data-code");
        var dataUrl = $(clickObj).attr("data-url");
        var dataT = {'dataId': dataId};
        let url = baseApiPath + '/module/sort/top/' + dataId;
        JsonpAjax(url, JSON.stringify(dataT), function (res) {
            console.log('record success !');
        });
        var path = baseSitePath.substring(0, baseSitePath.length - 1);
        var textHtml = $(clickObj).text();
        var rightContextLi = that.targetObj.find("#rightDataDiv").find("li[data-code='" + dataCode + "']");
        var isExists = rightContextLi.length > 0;
        if (isExists) {
            if (nowOpendRel != "") {//当前有选中窗口打开
                if (nowOpendRel != dataCode) {//当前选中的就是不是需要打开的，则需要影藏当前显示的，显示需要展现的,
                    openDataiv.removeClass("select");
                    that.targetObj.find("div#indexOperation").find("div").find("a[data-code='" + nowOpendRel + "']").hide();
                    that.targetObj.find("#rightDataDiv").find("ul>li[data-code='" + nowOpendRel + "']").hide();

                } else {
                    return;
                }
            }
            rightContextLi.fadeIn("slow");
            homeJsIn.targetObj.find("#labelMenuBtnListDiv").find("ul>li[data-code='" + dataCode + "']").addClass("select");
            //homeJsIn.targetObj.find("#indexOperation").find("ul>li[data-code='"+dataCode+"']").fadeIn("slow");
            homeJsIn.targetObj.find("div#indexOperation").find("div#move").find("a[data-code='" + dataCode + "']").fadeIn("slow");
        } else {
            if (nowOpendRel != "") {
                openDataiv.removeClass("select");
                that.targetObj.find("div#indexOperation").find("div#move").find("a[data-code='" + nowOpendRel + "']").hide();
                that.targetObj.find("#rightDataDiv").find("ul>li[data-code='" + nowOpendRel + "']").hide();
            }
            var addLi = $("<li style='height:100%;' data-code='" + dataCode + "'></li>");
            that.targetObj.find("#rightDataDiv").find("#rightDataDivUl").append(addLi);
            that.targetObj.find("#rightDataDiv").find("ul>li[data-code='" + dataCode + "']").load(path + dataUrl, function () {
                if (that.targetObj.find("#loginBgDiv").length > 0) {  //表示没有加载到html或者加载到登录页面，则跳转到登录页面
                    that.targetObj.empty();
                    loginTimeOut();
                    return;
                }
            }).css("margin-top", "400px").show().animate({marginTop: "0", opacity: "1"}, 500);
            //增加多标签页
            that.addLabelMenuBtn(dataCode, textHtml);
            that.addOperationBtn(dataCode);
        }
    },
    addLabelMenuBtn: function (rel, textHtml) {//增加多标签页
        //判断当前打开的标签数是否达到6个（含此次打开的）
        var templabelMenuBtn = this.targetObj.find("#labelMenuBtnListDiv").find("#labelMenuBtn");
        var templabelMenuBtnWidth = templabelMenuBtn.outerWidth();
        if (!this.showLeftRight) {
            var countlf = this.targetObj.find("#labelMenuBtnListDiv").find("ul>li").length;
            if (countlf == 6) {
                this.showLeftRight = true;
                this.targetObj.find("#labelMenuBtnListDiv").find("#aLeftBtn").show();
                this.targetObj.find("#labelMenuBtnListDiv").find("#aRightBtn").show();
            } else {
                this.showLeftRight = false;
            }
        } else {//打开超过6个后，后面打开的界面在最右边显示，最左边显示的被遮挡住。
            var labelMenuAlldiv = this.targetObj.find("#labelMenuBtnListDiv").find("#labelMenuAlldiv");
            var marginLeft = labelMenuAlldiv.css("marginLeft");
            if (isEmpty(marginLeft)) {
                marginLeft = 0;
            }
            marginLeft = parseInt(marginLeft);
            labelMenuAlldiv.css({"marginLeft": marginLeft - templabelMenuBtnWidth});
        }
        this.targetObj.find("#labelMenuBtnListDiv").find("ul>li").removeClass("select");
        var labelMenuBtn = this.targetObj.find("#labelMenuBtnListDiv").find("#labelMenuBtn").clone();
        labelMenuBtn.show();
        labelMenuBtn.attr("id", rel);
        labelMenuBtn.attr("data-code", rel);
        labelMenuBtn.find("a").attr('title', textHtml);
        labelMenuBtn.find("a").prepend(textHtml);
        this.targetObj.find("#labelMenuBtnListDiv").find("ul>li:last").before(labelMenuBtn);
        labelMenuBtn.addClass("select");
        labelMenuBtn.find("a").bind("click", function () {//点击标签页展示选中标签页
            homeJsIn.targetObj.find("#rightDataDiv").find("#indexHOMEDiv").hide();//隐藏HOME页
            var selectLableBtn = $(this).parent();
            var liClass = selectLableBtn.attr("class");
            if (liClass == "select") {//点击的是当前选中的，不做任何操作

            } else {//点击的是非当前选中的，页面切换
                var labelMenuBtnli = homeJsIn.targetObj.find("#labelMenuBtnListDiv").find("ul>li[class='select']");
                var lableRel = labelMenuBtnli.attr("data-code");
                var clickLableRel = selectLableBtn.attr("data-code");
                labelMenuBtnli.removeClass("select");
                homeJsIn.targetObj.find("#rightDataDiv").find("ul>li[data-code='" + lableRel + "']").hide();
                homeJsIn.targetObj.find("div#indexOperation").find("div").find("a[data-code='" + lableRel + "']").hide();//显示操作按钮显示的li
                selectLableBtn.addClass("select");
                homeJsIn.targetObj.find("#rightDataDiv").find("ul>li[data-code='" + clickLableRel + "']").show();
                homeJsIn.targetObj.find("div#indexOperation").find("div").find("a[data-code='" + clickLableRel + "']").show();//显示操作按钮显示的li
            }
        });
        var that = this;
        labelMenuBtn.find("a>span").bind("click", function () {//绑定点击关闭事件
            layer.closeAll();
            var liListObj = homeJsIn.targetObj.find("#labelMenuBtnListDiv").find("ul>li");
            var labelMenuBtnli = $(this).parent().parent();
            var selectCss = labelMenuBtnli.attr("class");
            if (liListObj.length > 2) {//不止打开一个界面
                var labelMenuAlldiv = homeJsIn.targetObj.find("#labelMenuBtnListDiv").find("#labelMenuAlldiv");
                if (liListObj.length == 7) {//当前打开的界面只有6个，关闭其中一个时
                    that.showLeftRight = false;
                    homeJsIn.targetObj.find("#labelMenuBtnListDiv").find("#aLeftBtn").hide();
                    homeJsIn.targetObj.find("#labelMenuBtnListDiv").find("#aRightBtn").hide();
                    labelMenuAlldiv.css("marginLeft", 30 + "px");
                }
                if (liListObj.length > 7) {//当前打开的界面超过6个，关闭的时候界面需要将左边移动
                    var marginLeft = labelMenuAlldiv.css("marginLeft");
                    if (isEmpty(marginLeft)) {
                        marginLeft = 0;
                    }
                    marginLeft = parseInt(marginLeft);
                    if (labelMenuBtnli.prev().length <= 0) {
                        labelMenuAlldiv.css("marginLeft", 30 + "px");
                    } else {
                        labelMenuAlldiv.css("marginLeft", (marginLeft + templabelMenuBtnWidth) + "px");
                    }
                }
                if (selectCss == "select") {//关闭的是当前选中的界面
                    var beforeLabelLi = labelMenuBtnli.prev();
                    if (beforeLabelLi.length == 0) {
                        beforeLabelLi = labelMenuBtnli.next();
                    }
                    var beforeHtmlLi = beforeLabelLi.attr("data-code");
                    beforeLabelLi.addClass("select");
                    homeJsIn.targetObj.find("#labelMenuBtnListDiv").find("ul>li[data-code='" + rel + "']").remove();//移除多标签显示的li
                    homeJsIn.targetObj.find("#rightDataDiv").find("ul>li[data-code='" + rel + "']").remove();//移除界面显示的li
                    homeJsIn.targetObj.find("div#indexOperation").find("div").find("a[data-code='" + rel + "']").remove();//移除操作按钮显示的li
                    homeJsIn.targetObj.find("#rightDataDiv").find("ul>li[data-code='" + beforeHtmlLi + "']").show();
                    homeJsIn.targetObj.find("div#indexOperation").find("div").find("a[data-code='" + beforeHtmlLi + "']").show();//显示操作按钮显示的li
                } else {//关闭的不是当前选中的界面
                    homeJsIn.targetObj.find("#labelMenuBtnListDiv").find("ul>li[data-code='" + rel + "']").remove();//移除多标签显示的li
                    homeJsIn.targetObj.find("#rightDataDiv").find("ul>li[data-code='" + rel + "']").remove();//移除界面显示的li
                    homeJsIn.targetObj.find("div#indexOperation").find("div").find("a[data-code='" + rel + "']").remove();//移除操作按钮显示的li
                }
            } else {//当前只有一个打开界面
                var labelMenuBtnliRel = labelMenuBtnli.attr("data-code");
                homeJsIn.targetObj.find("#labelMenuBtnListDiv").find("ul>li[data-code='" + labelMenuBtnliRel + "']").remove();//移除多标签显示的li
                homeJsIn.targetObj.find("#rightDataDiv").find("ul>li[data-code='" + labelMenuBtnliRel + "']").remove();//移除界面显示的li
                homeJsIn.targetObj.find("div#indexOperation").find("div").find("a[data-code='" + labelMenuBtnliRel + "']").remove();//移除操作按钮显示的li
                homeJsIn.targetObj.find("#rightDataDiv").find("#indexHOMEDiv").show();
                homeJsIn.targetObj.find("#homeSection").show();//隐藏HOME页
                homeJsIn.targetObj.find("#containsSection").hide();
            }
            //检查是否有websocket连接
            var dataCode = $(labelMenuBtnli).attr("data-code");
            websocketFunManager.removeWebSocket(dataCode);
        });
    },
    addOperationBtn: function (rel) {//增加操作按钮
        let url = baseApiPath + "basSystemResource/findUserBt/" + rel;
        JsonpAjax(url, null, function (result) {
            if (0 === result.code) {
                var operationUl = homeJsIn.targetObj.find("div#indexOperation div");
                operationUl.children().hide();
                if (result.data.constructor == Array) {
                    var data = result.data;
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            var o = data[i];
                            var a = $('<a data-code="' + rel + '" href="#" onclick="' + o.resourcePath + '"><span class="sp1"><img src="' + o.imgUrl + '"></span><span class="sp2">' + o.resourceName + '</span></a>');
                            operationUl.append(a);
                        }
                    } else {
                        operationUl.append($("<a></a>"));
                    }
                }
            }
        });
    },
    addLeftClick: function () {
        var that = this;
        this.targetObj.find("#labelMenuBtnListDiv").find("#aLeftBtn").bind("click", function () {
            if (!that.leftFlag) return;
            that.leftFlag = false;
            var countlf = that.targetObj.find("#labelMenuBtnListDiv").find("ul>li").length;
            var labelMenuAlldiv = that.targetObj.find("#labelMenuBtnListDiv").find("#labelMenuAlldiv");
            var marginLeft = labelMenuAlldiv.css("marginLeft");
            if (isEmpty(marginLeft)) {
                marginLeft = 0;
            }
            marginLeft = parseInt(marginLeft);
            var maxLeft = (30 - (countlf - 7) * 142);
            if (marginLeft == maxLeft) {//已经移动到最右边了，不能再移动了
                that.leftFlag = true;
                return;
            }
            var marginRight = (marginLeft - 142);
            labelMenuAlldiv.animate({"marginLeft": marginRight < maxLeft ? maxLeft : marginRight}, function () {
                that.leftFlag = true;
            });
        });
        this.targetObj.find("#labelMenuBtnListDiv").find("#aRightBtn").bind("click", function () {
            if (!that.leftFlag) return;
            that.leftFlag = false;
            var labelMenuAlldiv = that.targetObj.find("#labelMenuBtnListDiv").find("#labelMenuAlldiv");
            var marginLeft = labelMenuAlldiv.css("marginLeft");
            if (isEmpty(marginLeft)) {
                marginLeft = 0;
            }
            marginLeft = parseInt(marginLeft);
            if (marginLeft == 30) {//当移动到最左边时就不能再移动了
                that.leftFlag = true;
                return;
            }
            var marginRight = (marginLeft + 142);
            labelMenuAlldiv.animate({"marginLeft": marginRight <= 30 && marginRight >= 0 ? 30 : marginRight}, function () {
                that.leftFlag = true;
            })
        });
    },
    //通知
    kendoNotification: function () {
        var width = $(document.body).width() / 2 - 150;
        return this.targetObj.find("#notification").kendoNotification({
            position: {
                pinned: true,
                top: 200,
                right: width
            }, animation: {
                open: {
                    effects: "slideIn:left"
                },
                close: {
                    effects: "slideIn:right",
                    reverse: true
                }
            },
            hideOnClick: true,
            autoHideAfter: 3000,
            stacking: "right",
            templates: [{
                type: "success",
                template: $("#successTemplate").html()
            }, {
                type: "error",
                template: $("#errorTemplate").html()
            }, {
                type: "info",
                template: $("#infoTemplate").html()
            }]
        }).data("kendoNotification");
    },
    kendoNotificationConfirm: function () {
        var width = $(document.body).width() / 2 - 150;
        return this.targetObj.find("#notificationConfirm").kendoNotification({
            position: {
                pinned: true,
                top: 200,
                right: width
            },
            animation: {
                open: {
                    effects: "slideIn:left"
                },
                close: {
                    effects: "slideIn:right",
                    reverse: true
                }
            },
            hideOnClick: false,
            autoHideAfter: 0,
            stacking: "right",
            templates: [{
                type: "confirm",
                template: $("#confirmTemplate").html()
            }]
        }).data("kendoNotification");
    }
};

//提示信息通知         
function notification(showMsg, type, parameter) {
    if ("confirm" === type) {
        promptConfirm.show(showMsg, type);
        $(promptConfirm).data("params", parameter);
        $("div[class='success']").parent().parent().css("z-index", 10000);
        $(".overlayLoadingWord").css({
            'display': 'block',
            'opacity': '0.5'
        });
        return;
    }
    prompt.hide();
    prompt.show(showMsg, type);
}

function cancelPrompt() {
    promptConfirm.hide();
    $(".overlayLoadingWord").css({
        'display': 'none',
        'opacity': '0'
    });
}

function confirmPrompt() {
    var parameter = $(promptConfirm).data("params");
    if (typeof parameter["callback"] == "function") {
        eval(parameter["callback"])(parameter["parameter"]);
    }
    cancelPrompt();
} 
